package com.zzuli.practice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzuli.practice.entity.BatchIds;
import com.zzuli.practice.entity.Result;
import com.zzuli.practice.entity.User;
import com.zzuli.practice.service.impl.LoginService;
import com.zzuli.practice.service.impl.UserService;
import com.zzuli.practice.util.Constant;
import com.zzuli.practice.util.MDigest5;
import com.zzuli.practice.util.PageUtil;
import com.zzuli.practice.util.PracticeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @auther pony
 * @create 2022-07-05 15:17
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController implements Constant {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginService loginService;

    /**
     * 注册
     * @param userinfo
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@RequestBody User userinfo){
        //1、获取用户名和密码
        String username = userinfo.getUsername();
        String ouserpwd = userinfo.getPassword();

        Result result = new Result();

        //2、验证数据有效性
        if (username==null ||"".equals(username.trim())){
            result.setStatusCode(303);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (ouserpwd==null ||"".equals(ouserpwd.trim())){
            result.setStatusCode(303);
            result.setMessage("密码不能为空");
            return result;
        }

        //3、判断用户名是否存在
        try {
            User resultUser = userService.ckUsername(username);
            if (resultUser!=null){ //存在此用户
                result.setStatusCode(300);
                result.setMessage("注册失败，此用户名已被使用");
            }else {//不存在此用户
                //4、将密码加密
                String userpwd = MDigest5.getMD5(ouserpwd);
                //封装数据
                User user = new User();
                user.setUsername(username);
                user.setPassword(userpwd);
                user.setHeaderimg("http://localhost:8080/practice/header/headerimg/1.png");
                //添加用户
                Boolean aBoolean = userService.addUser(user);
                if (aBoolean){
                    result.setStatusCode(200);
                    result.setMessage("注册成功");

                }else {
                    result.setStatusCode(400);
                    result.setMessage("注册失败，请与管理员联系");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setStatusCode(500);
            result.setMessage("注册失败，请与管理员联系");
        }
        return result;
    }

    /**
     * 重置密码
     * @param
     * @return
     */
    @RequestMapping("/repwd")
    public Result repwd(@RequestBody User userinfo){
        //1、获取用户名和密码
        String username = userinfo.getUsername();
        String iuserpwd = userinfo.getPassword();

        Result result = new Result();

        //2、验证数据有效性
        if (username==null ||"".equals(username.trim())){
            result.setStatusCode(303);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (iuserpwd==null ||"".equals(iuserpwd.trim())){
            result.setStatusCode(303);
            result.setMessage("密码不能为空");
            return result;
        }

        //3、判断用户名是否存在
        try {
            User resultUser = userService.ckUsername(username);
            if (resultUser!=null){ //存在此用户
                //4、将密码加密
                String userpwd = MDigest5.getMD5(iuserpwd);
                //修改密码
                int i = userService.rePwd(username, userpwd);

                if (i == 1){
                    result.setStatusCode(200);
                    result.setMessage("修改成功");
                }else {
                    result.setStatusCode(400);
                    result.setMessage("修改失败，请与管理员联系");
                }
            }else {//不存在此用户
                result.setStatusCode(500);
                result.setMessage("修改失败，用户不存在");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setStatusCode(500);
            result.setMessage("修改失败，请与管理员联系");
        }
        return result;
    }

    /**
     * 查找是否存在此用户
     * @param
     * @return
     */
    @RequestMapping("/ckuser")
    public Result ckUserName(@RequestBody User userinfo){
        Result result = new Result();
        try {
            User reuserinfo = userService.ckUsername(userinfo.getUsername());
            if (reuserinfo!=null){ //用户已存在
                result.setStatusCode(200);
                result.setMessage("此用户名已被注册");
            }else {
                result.setStatusCode(404);
                result.setMessage("✔此用户名可以使用");
            }
        }catch (Exception e){
            result.setStatusCode(500);
            result.setMessage("查找用户名出错了，联系管理员");
        }
        return result;
    }

    // 修改密码
    @RequestMapping(value = "/updatepassword", method = RequestMethod.POST)
    public Result updatePassword(String username, String password, String newpassword){
        Result result = new Result();

        // 空值处理
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(newpassword)){
            result.setStatusCode(FAILURE);
            result.setMessage("账号密码不能为空");
            result.setData(null);
            return result;
        }

        // 检查账号密码
        User user = loginService.selectByName(username);
        if (user == null){
            result.setStatusCode(FAILURE);
            result.setMessage("账号不存在");
            result.setData(null);
            return result;
        }
        // 加密
        if (!user.getPassword().equals(PracticeUtil.md5(password + SECRET))){
            result.setStatusCode(FAILURE);
            result.setMessage("原密码错误");
            result.setData(null);
            return result;
        }

        // 验证成功，修改密码
        int i = userService.rePwd(username, PracticeUtil.md5(newpassword + SECRET));
        if (i == 1){
            result.setStatusCode(SUCCESS);
            result.setMessage("修改成功");
            result.setData(null);
            return result;
        } else {
            result.setStatusCode(FAILURE);
            result.setMessage("修改失败");
            result.setData(null);
            return result;
        }

    }

    /**
     * 用户添加
     * @param userinfo
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody User userinfo){
        //1、获取用户名和密码
        String username = userinfo.getUsername();
        String ouserpwd = userinfo.getPassword();

        Result result = new Result();

        //2、验证数据有效性
        if (username==null ||"".equals(username.trim())){
            result.setStatusCode(303);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (ouserpwd==null ||"".equals(ouserpwd.trim())){
            result.setStatusCode(303);
            result.setMessage("密码不能为空");
            return result;
        }

        //3、判断用户名是否存在
        try {
            User resultUser = userService.ckUsername(username);
            if (resultUser!=null){ //存在此用户
                result.setStatusCode(300);
                result.setMessage("添加失败，此用户名已被使用");
            }else {//不存在此用户
                //4、将密码加密
                userinfo.setPassword(MDigest5.getMD5(userinfo.getPassword()));
                // 设置默认头像
                userinfo.setHeaderimg("http://localhost:8080/practice/header/headerimg/1.png");

                //添加用户
                Boolean aBoolean = userService.addUser(userinfo);
                if (aBoolean){
                    result.setStatusCode(200);
                    result.setMessage("添加成功");
                }else {
                    result.setStatusCode(400);
                    result.setMessage("添加失败，请与管理员联系");
                }
            }
        }catch (Exception e){
            result.setStatusCode(500);
            result.setMessage("添加失败，请与管理员联系");
        }
        return result;
    }

    /**
     * 按id查询数据
     * @param id
     * @return
     */
    @RequestMapping("/findbyid/{id}")
    public Result findById(@PathVariable("id") Integer id){
        Result result = new Result();
        try{
            User model = userService.findById(id);
            if(model!=null){  // 存在此用户名
                result.setStatusCode(200);
                result.setMessage("success");
                result.setData(model);
            }
            else{ // 不存在此用户
                result.setStatusCode(300);
                result.setMessage("没有查找数据");
            }
        }catch (Exception ex){
            System.out.println(ex);
            result.setStatusCode(500);
            result.setMessage("查找数据出错，请与管理员联系");
        }
        return result;
    }
    @RequestMapping("/update")
    public Result update(@RequestBody User model){
        Result result = new Result();
        try{
            int rows = userService.update(model);
            if(rows>0){  // 存在此用户名
                result.setStatusCode(200);
                result.setMessage("已成功修改了工作人员的数据");
            }
            else{ // 不存在此用户
                result.setStatusCode(300);
                result.setMessage("修改工作人员失败");
            }
        }catch (Exception ex){
            System.out.println(ex);
            result.setStatusCode(500);
            result.setMessage("修改数据出错，请与管理员联系");
        }
        return result;
    }
    @RequestMapping("/del")
    public Result deleteBatchIds(@RequestBody BatchIds ids){
        Result result = new Result();
        try{
            int rows = userService.deleteBatch(ids.getIds());
            if(rows>0){  // 存在此用户名
                result.setStatusCode(200);
                result.setMessage("已成功删除工作人员的数据");
            }
            else{ // 不存在此用户
                result.setStatusCode(300);
                result.setMessage("删除工作人员失败");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(ex);
            result.setStatusCode(500);
            result.setMessage("删除数据出错，请与管理员联系");

        }


        return result;
    }

    @RequestMapping({"/getpagelist/{pageIndex}/{pageSize}/{keyword}","/getpagelist/{pageIndex}/{pageSize}"})
    public Result getPageList(@PathVariable("pageIndex") Integer pageIndex, @PathVariable("pageSize") Integer pageSize, @PathVariable(value = "keyword",required = false) String keyword){
        Result result = new Result();
        try{
            // 分页查询数据
            PageUtil<User> membersPage = userService.getUserinfoPage(pageIndex, pageSize,keyword);
            if(membersPage!=null){
                result.setStatusCode(200);
                result.setMessage("success");
                result.setData(membersPage);
            }
            else{
                result.setStatusCode(404);
                result.setMessage("没有查询到数据");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            result.setStatusCode(500);
            result.setMessage("查询数据出错，请与管理员了联系");
        }
        return result;
    }

}
